package cn.six1943.deepchat.module.ai.service.model;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.six1943.deepchat.module.ai.controller.admin.model.vo.*;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ProviderInstDO;
import cn.six1943.deepchat.module.ai.dal.dataobject.model.ModelDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.six1943.deepchat.module.ai.dal.mysql.model.ProviderInstOffcMapper;
import cn.six1943.deepchat.module.ai.dal.mysql.model.ModelMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.six1943.deepchat.module.ai.enums.ErrorCodeConstants.*;

/**
 * 模型密钥 Service 实现类
 *
 * @author at1943
 */
@Service
@Validated
public class ProviderInstOffcServiceImpl implements ProviderInstOffcService {

    @Resource
    private ProviderInstOffcMapper providerInstOffcMapper;
    @Resource
    private ModelMapper modelMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProviderInst(ProviderInstSaveReqVO createReqVO) {
        // 插入
        ProviderInstDO providerInst = BeanUtils.toBean(createReqVO, ProviderInstDO.class);
        providerInstOffcMapper.insert(providerInst);

        // 插入子表
        createModelList(providerInst.getId(), createReqVO.getModels());
        // 返回
        return providerInst.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProviderInst(ProviderInstSaveReqVO updateReqVO) {
        // 校验存在
        validateProviderInstExists(updateReqVO.getId());
        // 更新
        ProviderInstDO updateObj = BeanUtils.toBean(updateReqVO, ProviderInstDO.class);
        providerInstOffcMapper.updateById(updateObj);

        // 更新子表
        updateModelList(updateReqVO.getId(), updateReqVO.getModels());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProviderInst(Long id) {
        // 校验存在
        validateProviderInstExists(id);
        // 删除
        providerInstOffcMapper.deleteById(id);

        // 删除子表
        deleteModelByKeyId(id);
    }

    private void validateProviderInstExists(Long id) {
        if (providerInstOffcMapper.selectById(id) == null) {
            throw exception(PROVIDER_INST_NOT_EXISTS);
        }
    }

    @Override
    public ProviderInstDO getProviderInst(Long id) {
        return providerInstOffcMapper.selectById(id);
    }

    @Override
    public PageResult<ProviderInstDO> getProviderInstPage(ProviderInstPageReqVO pageReqVO) {
        return providerInstOffcMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（模型） ====================

    @Override
    public List<ModelDO> getModelListByKeyId(Long keyId) {
        return modelMapper.selectListByKeyId(keyId);
    }

    private void createModelList(Long keyId, List<ModelDO> list) {
        list.forEach(o -> o.setKeyId(keyId));
        modelMapper.insertBatch(list);
    }

    private void updateModelList(Long keyId, List<ModelDO> list) {
        deleteModelByKeyId(keyId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createModelList(keyId, list);
    }

    private void deleteModelByKeyId(Long keyId) {
        modelMapper.deleteByKeyId(keyId);
    }

}